﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DotNetCommon
{
    /// <summary>
    /// 表示机器信息
    /// </summary>
    public class Machine
    {
        static Machine()
        {
            SetMachineFlagByDefault();
        }

        #region 分布式集群中的机器Id
        private static int _machineId = 0;
        private static string _machineIdString = "";
        /// <summary>
        /// 机器Id,>=0，默认0, 根据集群的大小合理设置机器Id<para></para>
        /// 用在分布式Id生成中
        /// </summary>
        public static int MachineId { get => _machineId; }

        /// <summary>
        /// 机器IdString,默认: null，根据集群的大小合理设置机器IdString<para></para>
        /// 用在分布式流水号生成中，当值为null时，取 <see cref="Machine.MachineId"/>
        /// </summary>
        public static string MachineIdString
        {
            get
            {
                if (string.IsNullOrEmpty(_machineIdString)) return _machineId.ToString();
                return _machineIdString;
            }
        }

        /// <summary>
        /// 设置机器Id和机器IdString
        /// </summary>
        /// <param name="MachineId">机器Id, >=0，默认0, 用在分布式Id生成中</param>
        /// <param name="MachineIdString">机器IdString, 默认: null，用在分布式流水号生成中，当值为null时，取 <see cref="Machine.MachineId"/></param>
        public static void SetMachineId(int MachineId, string MachineIdString)
        {
            if (MachineId < 0) throw new Exception("MachineId的值必须大于等于0!");
            _machineId = MachineId;
            _machineIdString = MachineIdString;
        }

        /// <summary>
        /// 分别从环境变量、程序同目录下(<c>"machine.txt"</c>) 、程序父目录下(<c>"../machine.txt"</c>)中读取设置值，优先使用<c>"machine.txt"</c>中的. 
        /// </summary>
        /// <remarks>
        /// <c>"machine.txt"文件</c> 和 <c>环境变量</c> 格式：
        /// <para>MachineId=12</para>
        /// <para>MachineIdString=ABCD</para>
        /// <para></para>
        /// </remarks>
        public static void SetMachineFlagByDefault()
        {
            try
            {
                int machineId = 0;
                string machineIdString = null;
                //先从环境变量中读取
                var machineId2 = Environment.GetEnvironmentVariable("MachineId");
                if (!string.IsNullOrWhiteSpace(machineId2) && int.TryParse(machineId2, out int id))
                {
                    if (id >= 0) machineId = id;
                }
                var machineIdString2 = Environment.GetEnvironmentVariable("MachineIdString");
                if (!string.IsNullOrWhiteSpace(machineIdString2))
                {
                    machineIdString = machineIdString2.Trim();
                }
                //再从machine.txt文件中获取
                var filepath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
                filepath = Path.Combine(filepath, "machine.txt");
                #region 最多向上找6级
                try
                {
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "machine.txt");
                    }
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "..", "machine.txt");
                    }
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "..", "..", "machine.txt");
                    }
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "..", "..", "..", "machine.txt");
                    }
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "..", "..", "..", "..", "machine.txt");
                    }
                    if (!File.Exists(filepath))
                    {
                        filepath = Path.Combine(filepath, "..", "..", "..", "..", "..", "..", "machine.txt");
                    }
                }
                catch { }
                #endregion
                if (File.Exists(filepath))
                {
                    var lines = File.ReadAllLines(filepath);
                    var machineIdline = lines.FirstOrDefault(line => line.Trim().StartsWith("MachineId", StringComparison.OrdinalIgnoreCase));
                    if (!string.IsNullOrWhiteSpace(machineIdline))
                    {
                        try
                        {
                            machineId2 = machineIdline.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1];
                            if (int.TryParse(machineId2, out int id2))
                            {
                                if (id2 >= 0) machineId = id2;
                            }
                        }
                        catch { }
                    }
                    var machineIdStringline = lines.FirstOrDefault(line => line.Trim().StartsWith("MachineIdString", StringComparison.OrdinalIgnoreCase));
                    if (!string.IsNullOrWhiteSpace(machineIdStringline))
                    {
                        try
                        {
                            machineIdString = machineIdStringline.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
                        }
                        catch { }
                    }
                }
                _machineId = machineId;
                _machineIdString = machineIdString;
            }
            catch { }
        }
        #endregion
    }
}
